package com.jrx.anytxn.param.controller.system;

import com.google.common.collect.Maps;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.param.dto.system.ChannelTableReq;
import com.jrx.anytxn.param.dto.system.ChannelTableRes;
import com.jrx.anytxn.param.plugins.DeleteLog;
import com.jrx.anytxn.param.plugins.DeleteLogHelper;
import com.jrx.anytxn.param.service.system.IChannelTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jrx.auth.filter.model.User;
import jrx.auth.filter.service.InfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;

/**
 * 渠道表
 *
 * @author Yangxin
 * @date 2019/8/2
 */
@Api(tags = "页面渠道参数API接口")
@RestController
@RequestMapping(value = "/param/channels")
public class ChannelTableController {
    private static final Logger logger= LoggerFactory.getLogger(ChannelTableController.class);
    @Autowired
    IChannelTableService channelTableService;
    @Autowired
    private InfoService infoService;

    @ApiOperation(value = "根据渠道和租户Id查询渠道表信息", notes = "根据渠道和租户Id查询渠道表信息")
    @GetMapping(value = "/{channelId}/{tenantId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "channelId",value = "主键",required = true),
            @ApiImplicitParam(name = "tenantId",value = "租户ID",required = true)
    })
    public TxnRespResult<ChannelTableRes> getById(@NotNull @PathVariable String channelId,@PathVariable String tenantId) {
        TxnRespResult<ChannelTableRes> result = new TxnRespResult<>();
        ChannelTableRes res;
        try {
            res = channelTableService.findByChannelAndTenId(channelId,String.valueOf(infoService.getUser().getProjectId()));
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID分页查询渠道表信息",notes = "根据租户ID分页查询渠道表信息")
    @GetMapping(value = "/pageNum/{pageNum}/pageSize/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageNum",value="页码",required = true),
            @ApiImplicitParam(name="pageSize",value="页大小",required = true)})
    public TxnRespResult<TxnPage<ChannelTableRes>> getAllPage(@PathVariable(value = "pageNum") Integer pageNum,@PathVariable(value = "pageSize") Integer pageSize) {

        TxnRespResult<TxnPage<ChannelTableRes>> result = new TxnRespResult<>();
        TxnPage<ChannelTableRes> response;
        try {
            User user = infoService.getUser();
            System.out.println("USER的信息=="+user);
            String tenantId= String.valueOf(infoService.getUser().getProjectId());
            response = channelTableService.findAllPageByTenId(pageNum,pageSize,tenantId);
            result.getSuccess(response);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }

       return result;
    }

    @ApiOperation(value = "新增渠道表信息",notes = "新增渠道表信息")
    @PostMapping("/")
    public TxnRespResult<ChannelTableRes> createChannelTable(@RequestBody ChannelTableReq channelTableReq) {
        ChannelTableRes res;
        TxnRespResult<ChannelTableRes> result = new TxnRespResult<>();
        try {
            channelTableReq.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
            channelTableReq.setUpdateBy(infoService.getUser().getUserName());
            res = channelTableService.addChannelTable(channelTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "编辑渠道表信息",notes = "编辑渠道表信息")
    @PutMapping("/")
    public TxnRespResult<ChannelTableRes> modifyChannelTable(@RequestBody ChannelTableReq channelTableReq) {
        TxnRespResult<ChannelTableRes> result = new TxnRespResult<>();
        ChannelTableRes res;
        try {
            channelTableReq.setUpdateBy(infoService.getUser().getUserName());
            res = channelTableService.modifyChannelTable(channelTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }

        return result;
    }

    @ApiOperation(value = "根据渠道和租户ID删除渠道表信息",notes = "根据渠道和租户ID删除渠道表信息")
    @DeleteMapping(value = "/{channelId}/{tenantId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "channelId",value = "渠道ID",required = true),
            @ApiImplicitParam(name = "tenantId",value = "租户ID",required = true)
    })
    public TxnRespResult<Boolean> removeById(@NotNull @PathVariable String channelId,@PathVariable String tenantId) {
        TxnRespResult<Boolean> result = new TxnRespResult<>();
        Boolean flag;
        try {
            DeleteLog deleteLog = new DeleteLog(infoService.getUser().getUserName());
            DeleteLogHelper.setDelleteHistory(deleteLog);


            flag = channelTableService.removeByChannelaAndTenId(channelId, String.valueOf(infoService.getUser().getProjectId()));
            result.getSuccess(flag);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        } finally {
            DeleteLogHelper.clearLocalHistory();
        }
        return result;
    }

    @ApiOperation(value = "获得渠道表信息",notes = "获得渠道表信息")
    @GetMapping(value = "/list")
    public TxnRespResult<HashMap<String, List<ChannelTableRes>>> getAllList() {
        TxnRespResult<HashMap<String, List<ChannelTableRes>>> result = new TxnRespResult<>();

        String tenantId=String.valueOf(infoService.getUser().getProjectId());
        List<ChannelTableRes> allChannel = channelTableService.findAllChannel(tenantId);

        HashMap<String, List<ChannelTableRes>> sysCodeMap= Maps.newHashMap();
        sysCodeMap.put("listData",allChannel);
        return result.getSuccess(sysCodeMap);
    }

    @ApiOperation(value = "根据机构号获取有效渠道列表信息",notes = "根据机构号获取有效渠道列表信息")
    @GetMapping(value = "/list/orgId/{orgId}")
    @ApiImplicitParam(name="orgId",value="机构号",required = true)
    public TxnRespResult<HashMap<String, List<ChannelTableRes>>> getProductTableByOrgId(@PathVariable(value="orgId") String orgId) {
        logger.debug("get ProductTableByOrgId start");
        TxnRespResult<HashMap<String, List<ChannelTableRes>>> result = new TxnRespResult<>();

        List<ChannelTableRes> channelTableResList;
        try {
            String tenantId=String.valueOf(infoService.getUser().getProjectId());
            channelTableResList = channelTableService.findChannelListByOrgId(orgId,tenantId);
            HashMap<String, List<ChannelTableRes>> sysCodeMap= Maps.newHashMap();
            sysCodeMap.put("listData",channelTableResList);
            result.getSuccess(sysCodeMap);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        logger.debug("get ProductTableByOrgId end");
        return result;
    }
}
